<?php

namespace app\api\controller;

use addons\vip\library\Order;
use addons\vip\library\Service;
use app\admin\model\Bookclass;
use app\admin\model\Books;
use app\admin\model\books\BookShelf;
use app\admin\model\books\Browse;
use app\admin\model\moneyorder\Moneyorder;
use app\admin\model\vip\Viporder;
use app\admin\model\vip\Viprecore;
use app\common\controller\Api;
use app\common\model\User;
use Monolog\Handler\BrowserConsoleHandler;
use addons\vip\model\Record;
use addons\vip\model\Vip as VipModel;
use think\Db;

/**
 * 会员接口
 */
class Vip extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取会员价格列表
     * @ApiMethod (GET)
     **/
    public function vipList(){
        $list = (new \app\admin\model\Vip())->where('status','normal')->order('level desc')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 回调测试
     * @ApiMethod (POst)
     * @param int vip_id vip_id
     * @param int token token
     * @param int appid appid
     * @param int paytype 支付方式 alipay,wechat
     */
    /**
     * @return bool
     */
    public function huidiao()
    {
        $aa = (new Order)->settle(17,60,'购买');
        $this->success(__(''), $aa);
    }


    /**
     * 购买会员
     * @ApiMethod (POst)
     * @param int vip_id vip_id
     * @param int token token
     * @param int appid appid
     * @param int paytype 支付方式 alipay,wechat
     */
    public function submit(){
        $vip_id = $this->request->post('vip_id');
        $token = $this->request->post('token');
        $appid = $this->request->post('appid');
        $paytype = $this->request->post('paytype');
        $uid = $this->getToken($token);
        $userInfo = (new \app\admin\model\User())->find($uid);

//        $aa = (new Order)->settle(10,30,'购买');
//        $this->success(__(''), $aa);

        $vipInfo = (new VipModel())->where('id',$vip_id)->find();
        if (!$vipInfo) {
            $this->error('未找到VIP相关信息');
        }

        $userVip = (new Viprecore())->where(['user_id'=>$uid,'status'=>'active'])->find();

        if ($userVip && $userVip['level'] > $vipInfo['level']) {
            $this->error('当前VIP等级已高于购买的VIP等级');
        }
        if (!in_array($paytype, ['alipay', 'wechat'])) {
            $this->error('支付方式错误');
        }

        $amount = $vipInfo->price;
        $insert = [
            'user_id' => $uid,
            'vip_id'  => $vip_id,
            'level'   => $vipInfo->level,
            'days'    => $vipInfo->days,
            'amount'  => $vipInfo->price,
            'status'  => 'created',
        ];

        $vipRecord = Record::create($insert, true);
        $notifyurl = $this->request->root(true) . '/addons/epay/api/vipnotifyx/type/' . $paytype;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype ;
        $method = '';
        try {
            $response = \addons\vip\library\Order::submit($vipInfo->id, $vipRecord->id, $amount, $paytype, 'app', '', $notifyurl, $returnurl);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success(__(''), $response);
    }



    /**
     * 充值金币接口
     * @ApiMethod (POst)
     * @param int money_id 价格id
     * @param int token token
     * @param int paytype 支付方式 alipay,wechat
     */
    public function money(){
        $money_id = $this->request->post('money_id');
        $token = $this->request->post('token');
        $paytype = $this->request->post('paytype');
        $uid = $this->getToken($token);
        $userInfo = (new \app\admin\model\User())->find($uid);

        $moneyInfo = (new \app\admin\model\money\Money())->where('id',$money_id)->find();
        if (!$moneyInfo) {
            $this->error('未找到相关信息');
        }

        if (!in_array($paytype, ['alipay', 'wechat'])) {
            $this->error('支付方式错误');
        }

        $amount = $moneyInfo->price;
        $out_trade_no =date("YmdHis") . mt_rand(100000, 999999);
        $insert = [
            'user_id' => $uid,
            'money_id'   => $money_id,
            'orderid'   => $out_trade_no,
            'status'    => 'created',
            'amount'  => $amount,
            'beizhu'  => $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $paytype,
            'createtime'  => time(),
        ];

        $vipRecord = Moneyorder::create($insert, true);
        $returnurl = '/addons/epay/api/Vipnotifyx/type/alipay';

        //订单号
//        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        //订单标题
        $title = '充值金币';

        try {
            //回调链接
            $notifyurl = $this->request->root(true) . '/addons/epay/api/cznotifyxs/type/' . $paytype;
            $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype . '/out_trade_no/' . $out_trade_no;

            $response = \addons\epay\library\Service::submitOrder($amount, $out_trade_no, $paytype, $title, $notifyurl, $returnurl, 'app');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success(__(''), $response);
    }

    /**
     * 体验，仅供开发测试
     */
    public function experience()
    {
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }
        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);

        //订单标题
        $title = '测试订单';

        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);

        return $response;
    }



    /**
     * 支付成功，仅供开发测试
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = \addons\epay\library\Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            $info = (new Moneyorder())->where(['orderid'=>$out_trade_no])->find();

            if (!$info){
                return false;
            }
            (new Moneyorder())->where(['orderid'=>$out_trade_no])->update(['status'=>'paid']);
            User::money($payamount, $info['user_id'], '充值');
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
        }

        //下面这句必须要执行,且在此之前不能有任何输出

        if (\addons\epay\library\Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }






}
